#pragma once
#include <pthread.h>
#include <vector>
#include <functional>
#include <iostream>
#include <cassert>
#include <cstring>
#include "Log.hpp"

using namespace log_ddsm;
// 理解C++11做的工作，封装自己的原生线程
// 创建线程，执行任务
namespace ThreadMoudle
{
    // 支持模板
    using func_t = std::function<void(const std::string &name)>;

    // 线程控制-自主管理原生线程
    class Thread
    {
    private:
        // 线程创建后例行执行的函数
        static void *Routine(void *args) // 设置为static，防止this指针干扰类型匹配
        {
            Thread *self = static_cast<Thread *>(args);
            self->Excute();
            return nullptr;
        }

        void Excute()
        {
            _isrunning = true;
            _func(_name);
            _isrunning = false;
        }

    public:
        /// @brief 构造线程
        /// @param name 线程名
        /// @param func 线程要执行的任务
        Thread(const std::string &name, func_t func)
            : _name(name), _tid(), _isrunning(false), _func(func)
        {
        }

        bool Start()
        {
            int res = ::pthread_create(&_tid, nullptr, Routine, this); // 要求类型：void*（void*）——有this指针导致类型不匹配
            if (res != 0)
            {
                LOG(ERROR, "pthread_create failed with error: %s\n", strerror(res));

                // std::cerr << __FILE__ << " " << __LINE__ << ":" << "pthread_creat: error!" << std::endl;
                // printf("pthread_create failed with error: %s\n", strerror(res));

                return false;
            }
            else
            {
                return true;
            }
        }

        bool Stop()
        {
            if (_isrunning)
            {
                int res = ::pthread_cancel(_tid);
                if (res != 0)
                {
                    // std::cerr << __FILE__ << " " << __LINE__ << ":" << "pthread_cancel: error!" << std::endl;
                    // printf("pthread_cancel failed with error: %s\n", strerror(res));
                    LOG(ERROR, "pthread_cancel failed with error: %s\n", strerror(res));
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                // 不可能走到这里，Stop后不能再次Stop
                // assert(false);
                LOG(ERROR, "Stop after Stop\n");
                // std::cerr << "Stop after Stop" << std::endl;
                return false;
            }
        }

        // Stop之后join
        bool Join()
        {
            if (!_isrunning)
            {
                int res = ::pthread_join(_tid, nullptr);
                if (res != 0)
                {
                    // std::cout<<"Debug res:"<<res<<std::endl;

                    // std::cerr << __FILE__ << " " << __LINE__ << ":" << "pthread_join: error!" << std::endl;
                    // printf("pthread_join failed with error: %s\n", strerror(res));
                    LOG(ERROR, "pthread_join failed with error: %s\n", strerror(res));

                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                // Running时join
                LOG(ERROR, "join while Running\n");

                // std::cerr << "join while Running" << std::endl;
                return false;
            }
        }
        ~Thread() {}

        bool Status() { return _isrunning; }
        std::string Name() { return _name; }

    private:
        std::string _name; // 线程的名字
        pthread_t _tid;    // 线程的类型
        bool _isrunning;   // 线程是否在运行
        func_t _func;      // 线程将要执行的回调函数
    };

}; // namespace ThreadMoudle